<template>
	<div class="mc-popup-select-wrap">
		<div
			class="el-select"
			@click.stop="openDialog"
		>
			<div
				v-if="multiple"
				ref="tags"
				class="el-select__tags"
				:style="{
					'max-width': inputWidth - 32 + 'px',
					'width': '100%',
					'cursor': 'pointer',
				}"
			>
				<span v-if="collapseTags && tagsList.length">
					<Tag
						:closable="!selectDisabled"
						:size="collapseTagSize"
						type="info"
						disable-transitions
						@close="deleteTag($event, 0)"
					>
						<span class="el-select__tags-text">{{tagsList[0].name}}</span>
					</Tag>
					<Tag
						v-if="tagsList.length > 1"
						:closable="false"
						type="info"
						disable-transitions
					>
						<span class="el-select__tags-text">+ {{tagsList.length - 1}}</span>
					</Tag>
				</span>
				<transition-group
					v-if="!collapseTags"
					@after-leave="resetInputHeight"
				>
					<Tag
						v-for="(item, i) in tagsList"
						:key="item.id"
						:size="collapseTagSize"
						:closable="!selectDisabled"
						type="info"
						disable-transitions
						@close="deleteTag($event, i)"
					>
						<span class="el-select__tags-text">{{item.name}}</span>
					</Tag>
				</transition-group>
			</div>
			<Input
				ref="reference"
				v-model="innerValue"
				type="text"
				:placeholder="currentPlaceholder"
				:disabled="selectDisabled"
				readonly
				:validate-event="false"
				:tabindex="multiple ? '-1' : null"
				@mouseenter.native="inputHovering = true"
				@mouseleave.native="inputHovering = false"
			>
				<template #suffix>
					<i
						v-show="!showClose"
						:class="['el-select__caret', 'el-input__icon', 'el-icon-arrow-up']"
					/>
					<i
						v-if="showClose"
						class="el-select__caret el-input__icon el-icon-circle-close"
						@click="handleClearClick"
					/>
				</template>
			</Input>
		</div>
	</div>
</template>

<script>
import {addResizeListener, removeResizeListener} from 'element-ui/src/utils/resize-event';
import {magic} from '@lexmis/magic-ui/pc';
import {Tag, Input} from 'element-ui';
export default {
	name:'McUserSelect',
	components:{
		Tag, Input,
	},
	inject:{
		elForm:{
			default:'',
		},
		elFormItem:{
			default:'',
		},
	},
	props:{
		value:[Array, String],
		placeholder:{
			type:String,
			default:'请选择',
		},
		disabled:{
			type:Boolean,
			default:false,
		},
		multiple:{
			type:Boolean,
			default:false,
		},
		collapseTags:{
			type:Boolean,
			default:false,
		},
		clearable:{
			type:Boolean,
			default:true,
		},
		selectType:{
			type:String,
			default:'all',
		},
		size:{
			type:String,
			default:'',
		},
	},
	data(){
		return {
			innerValue:'',
			selectedData:[],
			tagsList:[],
			inputHovering:false,
			inputWidth:0,
			initialInputHeight:0,
		};
	},
	computed:{
		showClose(){
			const hasValue = this.multiple
				? Array.isArray(this.value) && this.value.length > 0
				: this.value !== undefined && this.value !== null && this.value !== '';
			const criteria
                = this.clearable && !this.selectDisabled && this.inputHovering && hasValue;
			return criteria;
		},
		currentPlaceholder(){
			if(this.multiple && Array.isArray(this.value) && this.value.length){
				return '';
			}else{
				return this.placeholder;
			}
		},
		selectDisabled(){
			return this.disabled || (this.elForm || {}).disabled;
		},
		_elFormItemSize(){
			return (this.elFormItem || {}).elFormItemSize;
		},
		selectSize(){
			return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
		},
		collapseTagSize(){
			return ['small', 'mini'].indexOf(this.selectSize) > -1 ? 'mini' : 'small';
		},
	},
	watch:{
		selectDisabled(){
			this.$nextTick(() => {
				this.resetInputHeight();
			});
		},
	},
	mounted(){
		addResizeListener(this.$el, this.handleResize);
		const reference = this.$refs.reference;
		if(reference && reference.$el){
			const sizeMap = {
				medium:36,
				small:32,
				mini:28,
			};
			const input = reference.$el.querySelector('input');
			this.initialInputHeight
                = input.getBoundingClientRect().height || sizeMap[this.selectSize];
		}
		if(this.multiple){
			this.resetInputHeight();
		}
		this.$nextTick(() => {
			if(reference && reference.$el){
				this.inputWidth = reference.$el.getBoundingClientRect().width;
			}
		});
		this.setDefault();
	},
	beforeUnmount(){
		if(this.$el && this.handleResize) removeResizeListener(this.$el, this.handleResize);
	},
	methods:{
		openDialog(){
			magic.base
				.selectPeople({
					selectType:['Member'],
					min:0,
					max:this.multiple ? -1 : 1,
					fillBackData:this.value ? Array.isArray(this.value) ? this.value : [this.value] : [],
				})
				.then((data) => {
					this.selectedData = data;
					if(data?.length){
						if(this.multiple){
							this.tagsList = data.map((item) => ({
								id:item.id,
								name:item.name,
							}));
							const selectedIds = data.map((item) => item.id);
							this.$emit('input', selectedIds);
							this.$emit('change', selectedIds, this.tagsList);
						}else{
							if(!data.length){
								this.innerValue = '';
								this.$emit('input', '');
								this.$emit('change', '', {});
								return;
							}
							this.innerValue = data[0].name;
							const selectedIds = data[0].id;
							this.$emit('input', selectedIds);
							this.$emit('change', selectedIds, data[0]);
						}
					}
				});
		},
		setDefault(){
			if(!this.value || !this.value.length){
				this.innerValue = '';
				this.selectedData = [];
				this.tagsList = [];
				this.$nextTick(() => {
					this.resetInputHeight();
				});
				return;
			}
			const userIds = Array.isArray(this.value) ? this.value : [this.value];
            // const hasSysItem = userIds.some(o => o === "currentUser");
			magic.core
				.service({
					url:'/api/magic-user/getUserByIds',
					method:'post',
					data:{
						userIds:userIds,
					},
				})
				.then(({data}) => {
					this.selectedData = data;
					if(this.multiple){
						this.innerValue = '';
						this.tagsList = this.selectedData.map((item) => ({
							id:item.userId,
							name:item.userName,
						}));
					}else{
						this.innerValue = this.selectedData.length
							? this.selectedData[0].userName
							: '';
					}
					this.$nextTick(() => {
						if(this.multiple){
							this.resetInputHeight();
						}
					});
				});
		},
		deleteTag(event, index){
			this.selectedData.splice(index, 1);
			this.tagsList.splice(index, 1);
			this.$emit(
				'input',
				this.selectedData.map((item) => item.id),
			);
			event.stopPropagation();
		},
		handleClearClick(event){
			this.selectedData = [];
			event.stopPropagation();
		},
		resetInputWidth(){
			this.$nextTick(() => {
				if(this.$refs.reference && this.$refs.reference.$el){
					this.inputWidth = this.$refs.reference.$el.getBoundingClientRect().width;
				}else{
					console.warn('reference节点未找到');
				}
			});
		},
		handleResize(){
			this.resetInputWidth();
			if(this.multiple)this.resetInputHeight();
		},
		resetInputHeight(){
			if(this.collapseTags) return;
			this.$nextTick(() => {
				if(!this.$refs.reference) return;
				const inputChildNodes = this.$refs.reference.$el.childNodes;
				const input = [].filter.call(inputChildNodes, (item) => item.tagName === 'INPUT')[0];
				const tags = this.$refs.tags;
				const tagsHeight = tags ? Math.round(tags.getBoundingClientRect().height) : 0;
				const sizeInMap = this.initialInputHeight || 40;
				input.style.height
                    = this.selectedData.length === 0
						? sizeInMap + 'px'
						: Math.max(
							tags ? tagsHeight + (tagsHeight > sizeInMap ? 6 : 0) : 0,
							sizeInMap,
						) + 'px';
			});
		},
	},
};
</script>
<style lang="scss" scoped></style>